# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render,redirect,render_to_response
from django.core.urlresolvers import reverse
from django.http import HttpResponse,HttpResponseRedirect
from django.views.generic import View

from userManager import userdao
from userManager.form import UserManagerForm
# Create your views here.
import logging 
import json

logger = logging.getLogger('django')

def signin(request):
	return render(request, 'user/signin.html')

def signup(request):
    return render(request, 'user/signup.html')
    
def logout(request):
    del request.session['user']
    return render(request, 'user/signin.html', {'login_msg': 'logout success'})

def dao_signin(request):
    if("POST"==request.method):
        username = request.POST["user_account"]
        password = request.POST["user_pwd"]
        if(userdao.userLoginCheck(username,password)):
            user = userdao.getOneUserByAccount(username)
            userInfo = {}
            userInfo['user_account'] = user.user_account
            userInfo['user_avatar'] = user.user_avatar.name
            request.session["user"]=userInfo
            return HttpResponseRedirect('/index/')
        else:
            return render(request, 'user/signin.html', {'login_msg': 'username or password is not right'},{'user_account':username})

def dao_signup(request):
    if("POST"==request.method):
        userMananger = UserManagerForm(request.POST)
        if(userdao.userCreate(request)):
            login_msg = 'create success'
        else:
        	login_msg = 'create false'
        return render(request, 'user/signin.html', {'login_msg': login_msg})

# 查找所有用户信息
def queryAllUser(request):
    users = userdao.getAllUser()
    return render(request, 'user/query.html', {'users': users})

# 获取所有用户的数量
def queryUserNum_ajax(request):
    userCount = userdao.getUserNum()
    return HttpResponse(userCount, content_type='application/json')

def delUserByAccount(request):
    if("POST"==request.method):
        _account = request.POST['user_account']
        userdao.delUserByAccount(_account)
        return HttpResponseRedirect('/user/queryAllUser')
    else:
        return HttpResponseRedirect('/user/queryAllUser')